﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;

namespace HttpProgram
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TestHttpWebRequest();
        }

        public static void TestHttpWebRequest()
        {
            List<int> l =new List<int>();
            l.Add(1);
            l.Add(2);
            //string url = "http://localhost:9000/studentController/saveOrUpdateStudent";
            string url = "http://localhost:9003/sms/adminController/saveOrUpdateAdmin";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            Student values = new Student() { name="张三",address="河南", id = 12, telephone = "12314455", score = l};
            
            //将对象转化为json字符串
            var str = JsonSerializer.Serialize(values);
           
            //设置请求头中Content-Type的值
            req.ContentType = "application/json";
            req.Method = "POST";
            byte[] data = Encoding.Default.GetBytes(str);
            using (Stream reqStream = req.GetRequestStream())
            {
                //写入数据到请求体，这一步并不是发送请求
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            //发送请求，等待并接收服务器的响应
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            string result;
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            
            Dictionary<string, object> dictionary = JsonSerializer.Deserialize<Dictionary<string, object>>(result);
            object value;
            dictionary.TryGetValue("code", out value);
            Console.WriteLine(value.ToString());
            Console.ReadKey();
        }
    }
}
